import store from "@/store";

import { TABLE_DATA_LOADING_FLAG, customNavbarHeight } from "$utils/enum";

/**
 * @param {Array} 表格数组
 * @param {function} 表格数据调用接口
 * @param {params} 调用接口参数
 * @param {Boolean} paging 是否有分页
 * @param {function} 回调方法
 * @returns 获取表格数据
 */
export const getDataGrid = async (api, params = {}, paging, db) => {
  try {
    const data = await api(params);
    // 有分页
    if (paging) {
      const { pages, current, records } = data || {};
      params.sumPages = pages;
      params.current = current;
      if (!db) {
        return records;
      } else {
        db(data.records || []);
      }
    } else {
      if (!db) {
        return data || [];
      } else {
        db(data || []);
      }
    }
  } catch (e) {
    console.log("接口报错");
    // TODO handle the exception
    return [];
  }
};

/**
 * @param {Array} 表格数组
 * @param {function} 表格数据调用接口
 * @param {params} 调用接口参数
 * @param {Boolean} paging 是否有分页
 * @param {function} 回调方法
 * @returns 新-获取表格数据
 */
export const newgetDataGrid = async (tableData, api, params = {}, paging, db) => {
  const { LOADING, MORE, NO_MORE } = TABLE_DATA_LOADING_FLAG

  try {
    // 加载中
    tableData.loading = LOADING
    const data = await api(params);
    // 有分页
    if (paging) {
      const { pages, records } = data || {};
      tableData.pagination.sumPageNum = pages
      tableData.loading = records?.length ? MORE : NO_MORE
      if (!db) {
        tableData.data = records;
      } else {
        db(records || []);
      }
    } else {
      if (!db) {
        tableData.data = data || [];
      } else {
        db(data || []);
      }
      tableData.loading = data?.length ? MORE : NO_MORE
    }
  } catch (e) {
    tableData.data = []
    tableData.loading = NO_MORE
    tableData.pagination.sumPageNum = 0
    tableData.pagination.pageNum = 1
    console.log("接口报错", e);
    // TODO handle the exception
    return [];
  }
};

/**
 * @param {Array} 表格数组
 * @param {function} 表格数据调用接口
 * @param {params} 调用接口参数
 * @param {Boolean} paging 是否有分页
 * @param {function} 回调方法
 * @returns 获取表格数据 2层
 */
export const getDataGrid2 = async (tableData, api, params = {}, paging, db) => {
  try {
    const data = await api(params);
    // 有分页
    if (paging) {
      if (!db) {
        tableData.data = data.records;
      } else {
        db(data.records || []);
      }
      params.sumPages = data.pages;
    } else {
      if (!db) {
        tableData.data = transitionArr(data || []);
      } else {
        db(data || []);
      }
    }
  } catch (e) {
    // TODO handle the exception
    return [];
  }
};

/**
 * @param {Array}  tableData 表格数组
 * @param {Object}  collectData 汇总数据
 * @param {function} api 表格数据调用接口
 * @param {params} 调用接口参数
 * @param {function} 回调方法
 * @returns 获取表格数据 (带汇总数据接口)
 */
export const getDataGrid3 = async (tableData, collectData, api, params = {}, db) => {
  const { LOADING, MORE, NO_MORE } = TABLE_DATA_LOADING_FLAG

  try {
    tableData.loading = LOADING
    const data = await api(params);
    const { records, count, group, sum } = data || {}

    tableData.loading = records?.length ? MORE : NO_MORE
    tableData.data = records || []

    Object.assign(collectData.mianData, {
      sum: sum || 0,
      count: count || 0,
    })
    if (group?.length) {
      Object.assign(collectData, {
        subheadData: group || [],
        subheadColumns: group.map(item => {
          const { key } = item
          return {
            label: key,
            prop: "value"
          }
        })
      })
    } else {
      Object.assign(collectData, {
        subheadData: [],
        subheadColumns: [],
      })
    }
    db(data || {});
  } catch (e) {
    tableData.loading = NO_MORE
    Object.assign(collectData, {
      subheadData: [],
      subheadColumns: [],
    })
    Object.assign(collectData.mianData, {
      sum: 0,
      count: 0,
    })
    tableData.data = []
  }
};

const transitionArr = (data) => {
  const arr = [];
  data.forEach((item) => {
    const obj = {
      leftName: item.key,
      titles: [],
      children: item.value,
    };

    arr.push(obj);
  });
  return arr;
};

/**
 * @param {Object}  params 返回参数
 * @param {String} backUrl 返回页面地址
 * @param {Number} backToPage 返回几个页面
 * @returns 获取表格数据 2层
 */
export const backPage = (params, backUrl, backToPage = 1) => {
  // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
  const pages = getCurrentPages();
  let prevPage = "";
  let pageIndex = -1;

  const newPages = pages.reverse();
  // 返回多个页面并不会清空多个页面  需要指定跳转页面
  for (let i = 0; i < newPages.length; i++) {
    const { route } = newPages[i];
    if (route === backUrl) {
      pageIndex = i;
      continue;
    }
  }

  prevPage = pages[pageIndex]; // 上一页页面实例
  console.log(prevPage, "prevPage");
  uni.navigateBack({
    delta: backToPage,
    success: () => {
      prevPage.$vm.setParams(params); // 给上一页绑定方法otherFun,传参地址id
    },
  });
};

/**
  * @param {object} form 查询条件
  * @param {string} field
  * @param {that} this
  * @return 将分页条件设置进查询条件中
  */
export const getPagination = (form, dataGrid) => {
  const { pageSize, pageNum } = dataGrid.pagination;
  const _data = {
    pageSize, pageNum,
    ...form
  };
  return _data;
};

/**
 * @returns 用户是否有对应权限
 */
export const getPermission = (code) => {
  const { permissionBtnCode } = store.getters;
  const flag = permissionBtnCode.includes(code);
  return flag;
};

/**
  * @param {array} whileList 不需要重置的白名单
  * @param {object} obj 需要重置的对象
  * @param {Function} db 回调方法
  * @description 重置白名单之外的所有内容
  */
export const reset = (whileList = [], form, db) => {
  Object.keys(form).forEach(key => {
    if (whileList.indexOf(key) === -1) {
      form[key] = emptyField(form[key]);
    }
  });

  // 回调方法
  db && db();
};

/**
  * @description 将字段内容清空
  */
export const emptyField = (str) => {
  if (!str || typeof str === "string" || typeof str === "number") {
    return "";
  } else if (Array.isArray(str)) {
    return [];
  } else if (typeof str === "boolean") {
    return false;
  } else {
    return {};
  }
};

/**
  * @description 设置表格高度
  */
export const setScrollHeigth = (searchHeight = 40, otherHeight = 0, buttomHeight = 45) => {
  let navBarH = 0

  // app时添加导航栏
  //  #ifdef APP-PLUS
  navBarH = customNavbarHeight
  //  #endif

  // 获取手机系统信息
  const info = uni.getSystemInfoSync();
  // 设置状态栏高度
  const statusBarHeight = info.statusBarHeight
  console.log(searchHeight, "searchHeight");
  const height = buttomHeight + searchHeight + navBarH + otherHeight + statusBarHeight
  return {
    height: `calc(100vh - ${height}px)`,
  }
}

